package com.atguigu.gmall.payment.controller;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayApiException;
import com.atguigu.gmall.common.exception.OrderException;
import com.atguigu.gmall.oms.entity.OrderEntity;
import com.atguigu.gmall.payment.config.AlipayTemplate;
import com.atguigu.gmall.payment.interceptors.LoginInterceptor;
import com.atguigu.gmall.payment.pojo.PayAsyncVo;
import com.atguigu.gmall.payment.pojo.PayVo;
import com.atguigu.gmall.payment.pojo.PaymentInfoEntity;
import com.atguigu.gmall.payment.pojo.UserInfo;
import com.atguigu.gmall.payment.service.PayService;
import com.rabbitmq.client.AMQP;
import org.apache.commons.lang3.StringUtils;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.Date;

@Controller
public class PayController {

    @Autowired
    private PayService payService;

    @Autowired
    private AlipayTemplate alipayTemplate;

    @Autowired
    private RabbitTemplate rabbitTemplate;

    @GetMapping("pay.html")
    public String paySelect(@RequestParam("orderToken")String orderToken, Model model){

        OrderEntity orderEntity = this.payService.queryOrder(orderToken);
        if (orderEntity == null) {
            throw new OrderException("您要支付的订单不存在！");
        }

        // 判断订单是否是待支付状态
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("该订单不可支付！");
        }

        // 判断该订单是否属于当前用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (orderEntity.getUserId() != userId) {
            throw new OrderException("订单不属于您，您当前无法支付！");
        }

        model.addAttribute("orderEntity", orderEntity);

        return "pay";
    }

    @GetMapping("alipay.html")
    @ResponseBody // 以其他视图形式展示方法的返回结果集
    public Object alipay(@RequestParam("orderToken")String orderToken){
        OrderEntity orderEntity = this.payService.queryOrder(orderToken);
        if (orderEntity == null) {
            throw new OrderException("您要支付的订单不存在！");
        }

        // 判断订单是否是待支付状态
        if (orderEntity.getStatus() != 0) {
            throw new OrderException("该订单不可支付！");
        }

        // 判断该订单是否属于当前用户
        UserInfo userInfo = LoginInterceptor.getUserInfo();
        Long userId = userInfo.getUserId();
        if (orderEntity.getUserId() != userId) {
            throw new OrderException("订单不属于您，您当前无法支付！");
        }

        try {
            // 调用支付宝接口，打开支付宝的支付页面
            PayVo payVo = new PayVo();
            payVo.setOut_trade_no(orderToken);
            // 这里一定要写0.01
            payVo.setTotal_amount("0.01");
            payVo.setSubject("谷粒商城支付平台");

            // 生成对账记录
            Long payId = this.payService.insertPayment(payVo);
            payVo.setPassback_params(payId.toString());

            return this.alipayTemplate.pay(payVo);
        } catch (AlipayApiException e) {
            e.printStackTrace();
        }
        throw new OrderException("跳转到支付页面失败，请重试！");
    }

    @GetMapping("pay/success")
    public String paySuccess(){

        return "paysuccess";
    }

    @PostMapping("pay/ok")
    @ResponseBody
    public String payOk(PayAsyncVo asyncVo){
        // 1.验签，确保该通知是支付宝发送的
        Boolean flag = this.alipayTemplate.checkSignature(asyncVo);
        if (!flag){
            return "failure";
        }

        // 2.校验业务参数：app_id、out_trade_no、total_amount
        String app_id = asyncVo.getApp_id();
        String out_trade_no = asyncVo.getOut_trade_no();
        String total_amount = asyncVo.getTotal_amount();
        String payId = asyncVo.getPassback_params();
        PaymentInfoEntity paymentInfoEntity = this.payService.queryPayment(payId);
        if (!StringUtils.equals(app_id, this.alipayTemplate.getApp_id())
                || !StringUtils.equals(out_trade_no, paymentInfoEntity.getOutTradeNo())
                || new BigDecimal(total_amount).compareTo(paymentInfoEntity.getTotalAmount()) != 0
        ) {
            return "failure";
        }

        // 3.校验状态trade_status TRADE_SUCCESS
        String trade_status = asyncVo.getTrade_status();
        if (!"TRADE_SUCCESS".equals(trade_status)){
            return "failure";
        }

        // 4.先修改支付对账表，发送消息给订单，完成订单状态的修改，并减库存
        paymentInfoEntity.setTradeNo(asyncVo.getTrade_no());
        paymentInfoEntity.setCallbackTime(new Date());
        paymentInfoEntity.setCallbackContent(JSON.toJSONString(asyncVo));
        paymentInfoEntity.setPaymentStatus(1);
        if (this.payService.updatePayment(paymentInfoEntity) == 1) {
            this.rabbitTemplate.convertAndSend("ORDER.EXCHANGE", "order.pay", out_trade_no);
        } else {
            // TODO：走退款流程
        }

        // 5.返回success
        return "success";
    }
}
